const camp=require("../../api/camp")
const goods=require("../../api/goods")
const { baseURL } = require("../../utils/request")


Page({
  

  /**
   * 页面的初始数据
   */
  data: {
   userId: wx.getStorageSync('userInfo').userId,
   activeKey: 0,
   campList: [],
   goodsList: [],
   baseURL: baseURL,
   cartList: [],
   cartLength: 0,
   showCart: false,
   amount: 0,
   campIdL: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('base',this.data.oss_url);
  console.log("wx.getSystemInfoAsync(userInfo)",wx.getStorageSync('userInfo'))
  this.getAppointmentCampList();
  
  },
  // 根据当前登陆用户id查询预约的营地
getAppointmentCampList() {
  camp.getAppointmentByUserId(wx.getStorageSync("userInfo").userId).then(res=>{
    console.log(res)
    if(res.code == 200) {
     this.setData({
      campList: res.data
     })
    }
    if (res.data.length <= 0) {
      return;
    }
    this.setData({
      campId: res.data[0].campId
    })
    let campId = res.data[0].campId
    this.getGoods(campId);
  })
},
// 当左侧营地切换时触发
onChange(event) {
  console.log("onChange event", event);
  this.setData({
    campId: this.data.campList[event.detail].campId
  })
  let campId = this.data.campList[event.detail].campId
  this.getGoods(campId);
},
// 根据营地id查询商品
getGoods (campId) {
  goods.goodsList({
    campId: campId
  }).then(res=>{
    console.log("goodsList", res)
    if(res.code == 200) {
      var _goodsList = res.data
      for (let i = 0; i < _goodsList.length; i++) {
        _goodsList[i].num = 0;
      }
     this.setData({
      goodsList: _goodsList
     })
     // 根据购物车缓存数据，调整商品右下角下标
     this.setCartList();
    }
  })
},
// 从本地存储中查询购物车数据
setCartList () {
  var cartList = wx.getStorageSync('cartList-' + this.data.campId)
  if (cartList && cartList.length > 0) {
    this.setData({
      cartList: cartList
    })
  } else {
    this.setData({
      cartList: []
    })
  }
  this.sumAmount();
  this.setGoodsNum();
},
// 设置商品已经加入购物车的数量
setGoodsNum() {
  
  var cartList = this.data.cartList;
  var goodsList = this.data.goodsList;
  for (let i = 0; i < cartList.length; i++) {
    const cartItem = cartList[i];
    for (let j = 0; j < goodsList.length; j++) {
      const goodsItem = goodsList[j];
      if (cartItem.goodsId == goodsItem.goodsId) {
        goodsList[j].num = cartItem.num;
        break;
      }
    }
  }
  this.setData({
    goodsList: goodsList
  })
},
// 当在商品数量变化时
onStepperChange (event) {
  console.log("onStepperChange event", event);
  let index = event.currentTarget.dataset.index;
  var goodsList = this.data.goodsList;
  var cartList = this.data.cartList;

  goodsList[index].num = event.detail;

  cartList.push(goodsList[index])
  const uniqueCartList = cartList.filter((item, index, self) => {
    return index === self.findIndex(obj => obj.goodsId === item.goodsId) && item.num > 0;
  });
  this.setData({
    goodsList: goodsList,
    cartList: uniqueCartList,
    cartLength: uniqueCartList.length
  })
  console.log("uniqueCartList", uniqueCartList)

  console.log("cartLength", this.data.cartLength)
  
  this.sumAmount();
},
// 当在购物车数量变化时
onCartStepperChange (event) {
  console.log("onCartStepperChange event", event);
  let index = event.currentTarget.dataset.index;
  var cartList = this.data.cartList;
  cartList[index].num = event.detail;
  const uniqueCartList = cartList.filter((item, index, self) => {
    return item.num > 0;
  });
  // 当购物车中的数量改变时，同步商品的下标
  var goodsList = this.data.goodsList;
  for (let j = 0; j < goodsList.length; j++) {
    if (cartList[index].goodsId == goodsList[j].goodsId) {
      goodsList[j].num = cartList[index].num;
      break;
    }
  }
  this.setData({
    cartList: uniqueCartList,
    goodsList: goodsList
  })
  this.sumAmount();
},
  // 计算总价
sumAmount() {
  var cartList = this.data.cartList;
  var amount = 0;
  for (let i = 0; i < cartList.length; i++) {
    const item = cartList[i];
    amount += item.num * item.goodsPrice;
  }
  this.setData({
    amount: amount,
    
    cartLength: cartList.length
  })
  wx.setStorageSync('cartList-' + this.data.campId, this.data.cartList)
},
// 弹出购物车页面
onShowCart() {
  this.setData({
    showCart: true
  })
},
// 弹出结算页面
onClickSettle(){
  this.setData({
    showSettle: true
  })
},
//关闭购物车界面
onClose(){
  this.setData({
    showCart: false,
    showSettle: false
  })
},
  getProvinceFromAddress(address) {
    // 地址字符串（示例）
    const addressStr = address;
   
    // 定义一个包含所有省级名称（包括自治区、直辖市等）的数组
    // 注意：这里只列出了部分示例，实际使用时需要补充完整
    const provinces = [
      '北京市', '天津市', '上海市', '重庆市', '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省',
      '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省',
      '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', '台湾省',
      '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
      '香港特别行政区', '澳门特别行政区'
    ];
   
    // 将地址字符串按空格分割成数组
    const addressParts = addressStr.split(' ');
   
    // 遍历分割后的数组，查找匹配的省级名称
    for (let i = 0; i < addressParts.length; i++) {
      const part = addressParts[i];
      console.log("part", part)
      for (let j = 0; j < provinces.length; j++) {
        const item = provinces[j];
        
        if (part.includes(item)) {
          return item; // 找到匹配的省级名称，返回
        }
      }
    }
   
    // 如果没有找到匹配的省级名称，返回null或空字符串
    return null; // 或 return '';
  },
getUserLocation(){
wx.getLocation({
  type: 'gcj02',
  success: (res)=>{
    console.log(res,"返回的数据")
    this.setData({
      latitude: res.latitude,
      longitude: res.longitude,
    });
    wx.chooseLocation({
      longitude: this.data.longitude,
      latitude: this.data.latitude,
      success: (res)=>{
        console.log("chooseLocation 返回的数据",res)
        console.log("getProvinceFromAddress 返回的数据",this.
        getProvinceFromAddress(res.address));
      }
    })
  }
})
  },
  onStepperChange(event){
    console.log("onStepperChange event",event);
    let index= event.currentTarget.dataset.index;
    var goodsList = this.data.goodsList;
    var cartList = this.data.cartList;
    goodsList[index].num= event.detail;
    cartList.push(goodsList[index])
    const uniqueCartList = cartList.filter((item, index,self)=>{
      return index === self.findIndex(obj =>obj.goodsId === item.goodsId);
    });
    this.setData({
      goodsList: goodsList,
      cartList: uniqueCartList,
      cartLength: uniqueCartList.length
    })  
    console.log("uniqueCartList",uniqueCartList)
  },
  onChange(event) {
    console.log("onChange event",event)
    let campId=this.data.campList[event.detail].campId;
    console.log("campid",campId);
    this.getGoods(campId);
  },

  // getAppointmentCampList(){
  //   console.log('用户id',this.data.userId);
  //   camp.getAppointmentByUserid(this.data.userId).then(res=>{
  //     console.log(res)
  //     if(res.code==200){
  //       this.setData({
  //         campList: res.data
  //       })
  //       console.log('campList',this.data);
  //     }
  //     if(res.data.length < 0){
  //       return;
  //     }
  //     let campId=res.data[0].campId
  //     this.getGoods(campId);
  //     })
  // },
  getGoods(campId){
    goods.goodsList({
      campId: campId
    }).then(res=>{
      if(res.code == 200){
        this.setData({
          goodsList: res.data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})